package com.ffcc.fitness.common.service.impl;

import com.ffcc.fitness.common.service.VerificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 邮箱验证服务实现类
 */
@Slf4j
@Service
public class VerificationServiceImpl implements VerificationService {
    
    private final StringRedisTemplate redisTemplate;
    private final JavaMailSender mailSender;
    
    @Value("${spring.mail.username:}")
    private String fromEmail;
    
    // 验证码有效期（分钟）
    private static final int CODE_EXPIRE_MINUTES = 5;
    
    // Redis key前缀
    private static final String EMAIL_CODE_PREFIX = "email:verification:code:";
    
    public VerificationServiceImpl(StringRedisTemplate redisTemplate, JavaMailSender mailSender) {
        this.redisTemplate = redisTemplate;
        this.mailSender = mailSender;
    }
    
    @Override
    public boolean sendEmailVerificationCode(String email) {
        try {
            // 生成验证码
            String code = generateCode();
            
            // 发送邮件
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(email);
            message.setSubject("器械通 - 场馆认领验证码");            message.setText(String.format(
                    "您好！\n\n" +
                    "您正在申请认领健身场馆，验证码为：%s\n\n" +
                    "验证码有效期为%d分钟，请及时使用。\n\n" +
                    "如果这不是您的操作，请忽略此邮件。\n\n" +
                    "器械通-一站式健身服务平台\n",
                    code, CODE_EXPIRE_MINUTES
            ));
            
            mailSender.send(message);
            
            // 存储验证码到Redis
            String key = EMAIL_CODE_PREFIX + email;
            redisTemplate.opsForValue().set(key, code, CODE_EXPIRE_MINUTES, TimeUnit.MINUTES);
            
            log.info("邮箱验证码发送成功: email={}, code={}", email, code);
            return true;
            
        } catch (Exception e) {
            log.error("发送邮箱验证码失败: email={}", email, e);
            return false;
        }
    }
    
    @Override
    public boolean verifyEmailCode(String email, String code) {
        try {
            String key = EMAIL_CODE_PREFIX + email;
            String storedCode = redisTemplate.opsForValue().get(key);
            
            if (storedCode == null) {
                log.warn("验证码不存在或已过期: email={}", email);
                return false;
            }
            
            boolean isValid = storedCode.equals(code);
            
            if (isValid) {
                // 验证成功后删除验证码
                redisTemplate.delete(key);
                log.info("邮箱验证码验证成功: email={}", email);
            } else {
                log.warn("邮箱验证码验证失败: email={}, code={}", email, code);
            }
            
            return isValid;
            
        } catch (Exception e) {
            log.error("验证邮箱验证码异常: email={}, code={}", email, code, e);
            return false;
        }
    }
    
    /**
     * 生成验证码
     */
    private String generateCode() {
        Random random = new Random();
        return String.format("%06d", random.nextInt(1000000));
    }
}
